package com.glory.brepda.activity.lanjian;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Build;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.fragment.app.FragmentManager;
import com.glory.brepda.R;
import com.glory.brepda.base.BaseActivity;
import com.glory.brepda.callback.CustomDialogEntityCallBack;
import com.glory.brepda.entity.LotAndPackagingfileEntity;
import com.glory.brepda.entity.VacuumExtraction;
import com.glory.brepda.entity.response.BaseResponseBean;
import com.glory.brepda.utils.NetUtils;
import com.glory.brepda.view.AddRemoveDropdownView;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralPop;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_PopUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StaticMembers;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import butterknife.BindView;
import butterknife.OnClick;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_SharePreferencesUtils;

public class BreLanjianVacuumExtractionActivity extends BaseActivity {

    @BindView(R.id.tvBCOPType)
    TextView tvBCOPType;
    @BindView(R.id.ivBCOPArrow)
    ImageView ivBCOPArrow;
    @BindView(R.id.flBCOPList)
    FrameLayout flBCOPList;

    @BindView(R.id.LayoutEqp)
    LinearLayout LayoutEqp;

    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.etLotID)
    FreeUI_ClearEditText etLotID;
    @BindView(R.id.etBeizu)
    FreeUI_ClearEditText etBeizu;
    @BindView(R.id.xinghao)
    EditText xinghao;
    @BindView(R.id.fengzuang)
    EditText fengzuang;
    @BindView(R.id.man)
    EditText man;
    @BindView(R.id.custcode)
    EditText custcode;
    @BindView(R.id.shuliang)
    EditText shuliang;
    @BindView(R.id.base_reel_num)
    EditText base_reel_num;
    @BindView(R.id.reel_num)
    EditText reel_num;
    @BindView(R.id.avg_num)
    EditText avg_num;
    @BindView(R.id.computer)
    Button computer;
    @BindView(R.id.tvBaseSubmit)
    TextView tvBaseSubmit;
    @BindView(R.id.tvREELType)
    TextView tvREELType;
    @BindView(R.id.ivREELArrow)
    ImageView ivREELArrow;
    @BindView(R.id.flREELList)
    FrameLayout flREELList;
    @BindView(R.id.man_sum)
    TextView man_sum;
    @BindView(R.id.ivshow)
    ImageView ivshow;

    private String WO_ID;
    private int MAIN_QTY;
    private int BASE_REEL_NUM;
    private int REEL_NUM;
    private String REEL_SIZE;
    private String TYPE;
    private String before2;
    private String after2;

    Set<String> mans = new HashSet<>();

//    private ImageView ivshow;
    private FreeUI_GeneralPop codePop,codePop2,codePop3;
    private ArrayList<String> city = new ArrayList<>(Arrays.asList("包抽一体","只包不抽","只抽不包","自动包装机"));
    private ArrayList<String> dimen = new ArrayList<>(Arrays.asList("7寸","13寸"));
    private ArrayList<String> eqpList = new ArrayList<>();
    
    String[] strList = null;
    boolean[] blList = null;
    private VacuumExtraction vacuumExtraction;

    private LotAndPackagingfileEntity entity;
//    private BreLanjianVacuumExtractionActivity.MTextWatcher textwatcher;

    // 机台下拉列表 viewModel
    AddRemoveDropdownView eqpDropdown;
    
    // 用于SharedPreferences的常量
    private static final String PREFS_FILE = "BRE_PDA_FILE";
    private static final String KEY_EQP_LIST = "VACUUM_EXTRACTION_EQP_LIST";
    private static final String DEFAULT_EQP = "P01,P02,P03";

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_bre_lanjian_vacuum_extraction;
    }

    @Override
    protected void initView() {
        // 初始化 机台下拉列表 viewModel
        eqpDropdown = findViewById(R.id.eqpDropdown);
        // 本地读取 eqpList 历史记录
        eqpList = pullEqpList();
        eqpDropdown.setItems(eqpList);

        // 设置 ItemsChanged 回调 , items 改变的时候 （如添加 ，删除） ， 直接同步到本地存储
        eqpDropdown.setOnItemsChangedListener(new AddRemoveDropdownView.OnItemsChangedListener(){
            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public void onItemsChanged(List<String> newItems) {
                // eqpList 同步到本地存储
                List<String> newEqpList = pushEqpList(newItems);
                // 同步内存中的 eqpList
                eqpList.clear();
                eqpList.addAll(newEqpList);
            }
        });

        String title = getIntent().getStringExtra(FreeApi_StaticMembers.SHOW_PLUGIN_KEY);
        tvTitle.setText(title);
        setMainLayout(llMain);
//        textwatcher = new MTextWatcher(man);
        searchEqpInfo(BreLanjianVacuumExtractionActivity.this, getSupportFragmentManager());

        man.addTextChangedListener(new  TextWatcher() {

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                before2 = String.valueOf(s);
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                after2 =  String.valueOf(s);
                // 只记录添加的 并且是扫描进来的数据
//                Log.d("扫描输","start:"+start+",before:"+before+"count:"+count);
                if(after2.length() > before2.length()){
                    String name = after2.substring(before2.length(),after2.length());
                    mans.add(name);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                Log.d("after",s.toString());
            }
        });

        flREELList.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (codePop2 != null) {
                    if (codePop2.isShowing()) {
                        codePop2.dismiss();
                    }
                } else {
                    codePop2 = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flREELList.getWidth(),dimen , ivREELArrow, (ty, i) -> {
                        tvREELType.setText(ty);
                        REEL_SIZE=ty;
                        Toast.makeText(getApplicationContext(),ty,Toast.LENGTH_SHORT).show();
                    });
                }
                FreeApi_PopUtils.setArrowShow(ivREELArrow);
                codePop2.showAsDropDown(flREELList, 0, 0);
            }
        });

        initEdit(etLotID, sa -> {
            //获取lot信息
            FreeUI_EntityCallBack<BaseResponseBean<LotAndPackagingfileEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<LotAndPackagingfileEntity>>
                    (new TypeToken<BaseResponseBean<LotAndPackagingfileEntity>>() {
                    }.getType(), getSupportFragmentManager(), this) {

                @Override
                public void onSuccess(Response<BaseResponseBean<LotAndPackagingfileEntity>> response) {
                    super.onSuccess(response);
                    if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                        entity = response.body().getResponse().getBody();
                        inputvalue(entity);
                        showToast("成功", true);
                        etLotID.requestFocus();

                    }
                }

                @Override
                public void onError(Response<BaseResponseBean<LotAndPackagingfileEntity>> response) {
                    super.onError(response);
                    loadError(response.getException(), "失败");
                }
            };
            JsonObject map = new JsonObject();
            map.addProperty("LOT_ID", getText(etLotID));
            map.addProperty("ACTION_TYPE", "QUERY");
            NetUtils.requestPostNet("IF.PDA_QUERY_LOT_PACKS", "Common", getApplication(), map, callBack);
        });

        // 界面加载就执行的方法

        flBCOPList.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (codePop != null) {
                    if (codePop.isShowing()) {
                        codePop.dismiss();
                    }
                } else {
                    codePop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flBCOPList.getWidth(), city, ivBCOPArrow, (ty, i) -> {
                        tvBCOPType.setText(ty);
                        TYPE=ty;
                        Toast.makeText(getApplicationContext(),ty,Toast.LENGTH_SHORT).show();

                        if(TYPE.equals("自动包装机")){
                            LayoutEqp.setVisibility(View.VISIBLE);
                        }else{
                            LayoutEqp.setVisibility(View.GONE);
                            eqpDropdown.setInputText(null);
                        }

                    });
                }
                FreeApi_PopUtils.setArrowShow(ivBCOPArrow);
                codePop.showAsDropDown(flBCOPList, 0, 0);
            }
        });

    }

    @OnClick({R.id.tvBaseSubmit,R.id.ivshow,R.id.computer})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tvBaseSubmit:
                submit();
                break;
            case R.id.ivshow:
                ivshow.setRotationY(180);
                showDialogSelect(view);
                break;
            case R.id.computer:
                computered(view);
                break;
        }
    }

    private void submit(){

        if(getText(etLotID).equals("")){
            showToast("请先扫描批次信息", false);
            return;
        }
        if(REEL_SIZE == null || REEL_SIZE.equals("")){
            showToast("请选择盘尺寸", false);
            return;
        }
        if(TYPE == null || TYPE.equals("")){
            showToast("请选择抽真空方式", false);
            return;
        }
        if(getText(man).equals("")){
            showToast("请选择操作工", false);
            return;
        }
        if(man_sum.getText().equals("") || getText(avg_num).equals("")){
            showToast("请先计算！", false);
            return;
        }

        if(StringUtils.isNotEmpty(TYPE) && this.TYPE.equals("自动包装机") && StringUtils.isEmpty(eqpDropdown.getInputText())){
            showToast("自动包装机必须选择一台设备！", false);
            return;
        }

        FreeUI_EntityCallBack<BaseResponseBean<JSONObject>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<JSONObject>>
                (new TypeToken<BaseResponseBean<JSONObject>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<JSONObject>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    showToast("成功", true);
                }
                btnClean1();
                etLotID.requestFocus();
            }

            @Override
            public void onError(Response<BaseResponseBean<JSONObject>> response) {
                super.onError(response);
                loadError(response.getException(), "PDA_QUERY_LOT_PACKS");

            }
        };
        JsonObject map = new JsonObject();

        map.addProperty("WO_ID", WO_ID);
        map.addProperty("LOT_ID", getText(etLotID));
        map.addProperty("MAIN_QTY", MAIN_QTY);
        map.addProperty("BASE_REEL_NUM", BASE_REEL_NUM);
        map.addProperty("REEL_NUM", getText(reel_num));
        map.addProperty("CUSTOMER_CODE", getText(custcode));
        map.addProperty("MAIN_MAT_TYPE", getText(fengzuang));
        map.addProperty("PRODUCT_MODEL", getText(xinghao));
        map.addProperty("REEL_SIZE",REEL_SIZE);
        map.addProperty("MANS",getText(man));
        map.addProperty("MAN_NUM",Integer.parseInt(man_sum.getText().toString()));
        map.addProperty("AVG_NUM",Double.parseDouble(getText(avg_num)));
        map.addProperty("TYPE",TYPE);

        map.addProperty("EQP",eqpDropdown.getInputText());
        map.addProperty("BeiZu",getText(etBeizu));

        map.addProperty("ACTIONTYPE", "SAVE");
        NetUtils.requestPostNet("IF.PDA_VE_OUTPUT", "Common", BreLanjianVacuumExtractionActivity.this, map, callBack);
    }

    private void btnClean1(){
        etLotID.setText("");
        xinghao.setText("");
        fengzuang.setText("");
        custcode.setText("");
        tvBCOPType.setText("");
        tvREELType.setText("");
        shuliang.setText("");
        base_reel_num.setText("");
        reel_num.setText("");
        avg_num.setText("");
        etBeizu.setText("");
        REEL_SIZE="";
        TYPE="";
        etLotID.requestFocus();
        eqpDropdown.setInputText("");
    }

    private void showDialogSelect(View view){

            // 查詢用戶的，返回用戶列表

            if(vacuumExtraction.getPMSLIST().size()<=0){
                showToast("无法获取用户列表，请检查！",false);
            }
            // 列表转字符数组
            strList = vacuumExtraction.getPMSLIST().toArray(new String[0]);
            blList = new boolean[strList.length];
            for(int i=0;i<strList.length;i++){
                blList[i] = false;
            }

            if(man != null){
                for (int i = 0; i < strList.length; i++) {
                    if(getText(man).contains(strList[i])){
                        blList[i]=true;
                    }
                }
            }

            AlertDialog.Builder aBuilder = new AlertDialog.Builder(BreLanjianVacuumExtractionActivity.this);
            aBuilder.setTitle("请选择操作工: ");
            // 创建多选对话框的内容
            aBuilder.setMultiChoiceItems(strList, blList, new DialogInterface.OnMultiChoiceClickListener() {
                // 取消或勾选对话框内的单选框
                @Override
                public void onClick(DialogInterface dialogInterface, int i, boolean b) {
                    blList[i] = b;
                }
            });

            aBuilder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    // 获取勾选到的文本并打印
                    String txt = "";
                    for(short index=0;index<blList.length;++index){
                        if(blList[index]){
                            txt += (strList[index]+" ");
                        }
                    }
                    Log.d("选择操作工: ",strList.toString());
                    man.setText(txt);
                    // 取消内部已勾选
                    cancelBool();
                }
            });

            // 点击对话框外,进行取消对话框事件
            aBuilder.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialogInterface) {
                    // 取消内部已勾选
                    cancelBool();
                }
            });

            aBuilder.show();

        man.setText(null);

    }

    // 查询抽真空的人员名单
    public void searchEqpInfo(Context context, FragmentManager fragmentManager) {
        FreeUI_EntityCallBack<BaseResponseBean<VacuumExtraction>> callBack = new CustomDialogEntityCallBack<BaseResponseBean<VacuumExtraction>>
                ("正在查询人员名单", new TypeToken<BaseResponseBean<VacuumExtraction>>() {
                }.getType(), fragmentManager, context) {

            @Override
            public void onSuccess(Response<BaseResponseBean<VacuumExtraction>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(context,false,fragmentManager)){
                    if (response.body().getResponse().getBody() != null){
                        vacuumExtraction = response.body().getResponse().getBody();
                    }
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<VacuumExtraction>> response) {
                super.onError(response);
            }
        };

        JsonObject map = new JsonObject();
        map.addProperty("ACTIONTYPE", "NAMELIST");
        NetUtils.requestPostNet("IF.PDA_VE_OUTPUT", "Common", context, map, callBack);
    }

    // 取消内部已勾选
    private void cancelBool(){
        for(short index=0;index<blList.length;++index){
            blList[index] = false;
        }
    }

    private void  inputvalue(LotAndPackagingfileEntity entity){

        WO_ID = entity.getLOT().getWOID();
        MAIN_QTY = Integer.parseInt(entity.getLOT().getMAINQTY());
        BASE_REEL_NUM = Integer.parseInt(entity.getPACKS().getReelNum());
        REEL_NUM = (int)  Math.ceil(MAIN_QTY * 1.0 / BASE_REEL_NUM);
        etLotID.setText(entity.getLOT().getLOTID());
        xinghao.setText(entity.getLOT().getUDF().getProductModel());
        fengzuang.setText(entity.getLOT().getMAINMATTYPE());
        custcode.setText(entity.getLOT().getCUSTOMERCODE());
        shuliang.setText(String.valueOf(MAIN_QTY));
        base_reel_num.setText(String.valueOf(BASE_REEL_NUM));
        reel_num.setText(String.valueOf(REEL_NUM));
    }

    private void  computered(View view){
        if(getText(man).equals("")){
            showToast("请选择操作工", false);
            return;
        }
        if(getText(etLotID).equals("")){
            showToast("请先扫描批次", false);
            return;
        }
        if(REEL_SIZE.equals("") || REEL_SIZE==null){
            showToast("请选择盘尺寸", false);
            return;
        }
        if(TYPE.equals("") || TYPE == null){
            showToast("请选择抽真空方式", false);
            return;
        }
        // 员工只能是中文和空格
//        if (getText(man).matches("[\\s|\\u4e00-\\u9fa5]+")) {
//            showToast("操作工只能存在中文或者空格", false);
//            return;
//        }
        // 查询集合item是否包含界面字符串子项，不包含着必须剔除。
//        List<String> manss = new ArrayList<>(mans);
//        List<String> remove = new ArrayList<>();
//        for (String item:manss
//             ) {
//            if(!getText(man).contains(item)){
//                remove.add(item);
//            }
//        }
//        List<String> result = manss.stream().filter(i -> !remove.contains(i)).collect(Collectors.toList());
        // 拼接Set
        List<String> result = Arrays.asList(getText(man).split(" "));
        String manman = "";
        for (String item: result
             ) {
            manman+=item+" ";
        }
        String results = manman.trim();
        man.setText(results);

        int n = result.size();
        man_sum.setText(String.valueOf(n));
        double av = Integer.parseInt(getText(reel_num)) * 1.0 / n;
        avg_num.setText(String.format("%.2f",av));
        mans.clear();
        mans = new HashSet<>(result);
        before2 = results;
    }

    @Override
    protected void initData() {

    }

    /**
     * 从本地存储中获取 EQP_LIST
     * @return
     */
    private ArrayList<String> pullEqpList(){
        // 从本地读取 EQP_LIST 并去重、保序
        String stored = FreeApi_SharePreferencesUtils.getSharePre(
                PREFS_FILE,
                KEY_EQP_LIST,
                DEFAULT_EQP,
                com.glory.brepda.base.MyApp.app
        );
        LinkedHashSet<String> set = new java.util.LinkedHashSet<>();
        if (stored != null) {
            for (String s : stored.split(",")) {
                s = s.trim();
                if (!org.apache.commons.lang3.StringUtils.isEmpty(s)) {
                    set.add(s);
                }
            }
        }
        return new ArrayList<>(set);
    }

    /**
     * 同步 eqpList 到本地存储
     * @return
     */
    @RequiresApi(api = Build.VERSION_CODES.O)
    private ArrayList<String> pushEqpList(List<String> newItems){
        // 去重、保序并持久化
        LinkedHashSet<String> newSet = new java.util.LinkedHashSet<>();
        for (String s : newItems) {
            if (!StringUtils.isEmpty(s)) {
                newSet.add(s.trim());
            }
        }
        String updatedString = String.join(",", newSet);
        FreeApi_SharePreferencesUtils.setSharePre(
                PREFS_FILE,
                KEY_EQP_LIST,
                updatedString,
                com.glory.brepda.base.MyApp.app
        );
        return new ArrayList<>(newSet);
    }

//    public class MTextWatcher implements TextWatcher {
//
//        private EditText name;
//        MTextWatcher(EditText name){
//            this.name = name;
//        }
//        @Override
//        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//            Log.d("ssssssssssss",s.toString());
//        }
//
//        @Override
//        public void onTextChanged(CharSequence s, int start, int before, int count) {
//
//        }
//
//        @Override
//        public void afterTextChanged(Editable s) {
//            Log.d("aaaaaa",s.toString());
//            man.setText(s.toString()+" ");
//        }
//    }
}